package com.evan.uyclub.HomeFragment;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.text.format.Time;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import com.evan.uyclub.GameBa.GameWeb;
import com.evan.uyclub.Other.Utlis;
import com.evan.uyclub.R;
import com.gigamole.navigationtabstrip.NavigationTabStrip;
import com.robinhood.ticker.TickerUtils;
import com.robinhood.ticker.TickerView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.skydoves.elasticviews.ElasticCardView;
import com.squareup.picasso.Picasso;
import com.tapadoo.alerter.Alerter;
import com.umeng.analytics.MobclickAgent;
import com.zhouyou.http.EasyHttp;
import com.zhouyou.http.callback.SimpleCallBack;
import com.zhouyou.http.exception.ApiException;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import xyz.doikki.videoplayer.controller.GestureVideoController;
import xyz.doikki.videoplayer.exo.ExoMediaPlayer;
import xyz.doikki.videoplayer.exo.ExoMediaPlayerFactory;
import xyz.doikki.videoplayer.player.VideoView;

public class HappyFragment extends LazyFragment {

    String[] UrlData = {"https://www.yikm.net/play?id=4138&n=L2Zjcm9tL3NqL0NvbnRyYSAoKzQgbWVudSkubmVz&t=%E9%AD%82%E6%96%97%E7%BD%97(%E7%BE%8E%E7%89%88)4%E5%90%881&ac=3&p=/fcpic/sj/910a.png",
            "https://www.yikm.net/play?id=3501&n=L2Zjcm9tL2R6bXgvU3VwZXIgTWFyaW8gQnJvcy4gKFcpIFshXS5uZXM=&t=%E8%B6%85%E7%BA%A7%E9%A9%AC%E9%87%8C%E5%A5%A5&ac=3&p=/fcpic/2146a.png",
            "https://www.yikm.net/play?id=4511&n=L2Zjcm9tL3h5eC9Tbm93IEJyb3MuIChKKS5uZXM=&t=%E9%9B%AA%E4%BA%BA%E5%85%84%E5%BC%9F&ac=3&p=/fcpic/xyx/2023a.png",
            "https://www.yikm.net/play?id=4275&n=L2Zjcm9tL3h5eC9CYXR0bGUgQ2l0eSAoSikgWyFdLm5lcw==&t=%E5%9D%A6%E5%85%8B%E5%A4%A7%E6%88%98&ac=3&p=/fcpic/xyx/timg.png",
    };
    private View view;
    private ImageView Music_icon, bizhi, touxiang, vid_img1, vid_img2;
    private TextView Music_name;
    private Random random = new Random();
    private ElasticCardView bizhi_dow, touxiang_dow, game_one, game_two, game_three, game_forr, Music_play, Music_stop, Music_refer, Video_next_one, Video_next_two, Video_next_one_stop, Video_next_two_stop;
    private VideoView<ExoMediaPlayer> Video_one, Video_two;
    private int musicint = random.nextInt(13);
    private String[] music = {
            "488249475",
            "1441758494",
            "496370620",
            "1808492017",
            "1859245776",
            "1827600686",
            "1388961672",
            "1361232228",
            "1403223749",
            "1304788674",
            "1836118949",
            "1325896666",
            "1456677611"
    };
    private String[] Musicname = {
            "哪里都是你",
            "晚风",
            "断线",
            "错位时空",
            "STAY",
            "还是会想你",
            "NUMB",
            "Hnpbaha",
            "最好的自己",
            "Lagoon",
            "不知道路还有多长",
            "Fiery Sky",
            "Temple"
    };
    private String music_url = "https://link.hhtjim.com/163/" + music[musicint] + ".mp3";
    private String music_name = Musicname[musicint];
    /*private int musicimgs = Random.Default.nextInt(10);
     private int musics= random.nextInt(10);*/
    private int[] musicimg = {
            R.mipmap.a60, R.mipmap.a61, R.mipmap.a62, R.mipmap.a63, R.mipmap.a64, R.mipmap.a65, R.mipmap.a66, R.mipmap.a67, R.mipmap.a69, R.mipmap.a5z
    };
    /*private String ceshiurl = "https://link.hhtjim.com/163/5146554.mp3";*/
    private MediaPlayer mediaPlayer;
    private String[] data = {
            "https://dwz.mk/FvQVNb",
            "http://b6i.cn/6yHq3",
            "http://mtw.so/66fctR",
            "http://mtw.so/6d5rQ6",
            "http://mtw.so/6llOO4",
            "http://mtw.so/5JKMrO",
            "http://mtw.so/66faVz",
            "https://dwz.mk/Q3YBjm",
            "https://dwz.mk/MVZVjy",
            "http://mtw.so/6llPR4",
            "http://mtw.so/6sS2VL",
            "http://mtw.so/5YNa04",
            "http://mtw.so/6llPRe",
            "http://mtw.so/5Ceznr",
            "http://mtw.so/6d5qi8",
            "http://mtw.so/5uImiU",
            "http://mtw.so/6d5qii",
            "http://mtw.so/5JKMu4",
            "http://mtw.so/6llPRI",
            "http://mtw.so/5uImkQ",
            "http://mtw.so/5YNa2k",
            "http://mtw.so/6llPRS",
            "http://mtw.so/5JKMuo",
            "http://mtw.so/6d5qiM",
            "http://mtw.so/6llPS2",
            "http://mtw.so/5JKMuy",
            "http://mtw.so/5YNa2E"
    };

    /*@Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_happy, container, false);
        return view;
    }*/

    @Override
    protected int getContentViewId() {
        return R.layout.fragment_happy;
    }


    @Override
    protected void initView(View views) {
        view = views;
    }

    @Override
    protected void initData() {
        initStartData();
    }

    @Override
    protected void initEvent() {
        initId();
        initUI();
        Start();
    }

    private void initId() {

        //实现回弹效果，支持带列表的。
        SmartRefreshLayout home_smart = (SmartRefreshLayout) view.findViewById(R.id.happy_smart);
        home_smart.setEnableLoadMore(true);
        home_smart.setEnablePureScrollMode(true);
        //设置对应xml界面的字体
        TextView up_title = view.findViewById(R.id.up);
        TextView cloud_title = view.findViewById(R.id.cloud);
        up_title.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "english.ttf"));
        cloud_title.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "english.ttf"));
        final NavigationTabStrip navigationTabStrip = (NavigationTabStrip) view.findViewById(R.id.happy_tab);
        //navigationTabStrip.setTypeface(Typeface.createFromAsset(requireActivity().getAssets(), "space.ttf"));
        navigationTabStrip.setTabIndex(0, true);
        final TickerView happy_text_shu = (TickerView) view.findViewById(R.id.happy_text_shu);
        happy_text_shu.setCharacterLists(TickerUtils.provideNumberList());
        mediaPlayer = new MediaPlayer();

        Music_icon = view.findViewById(R.id.happy_music_icon);
        Music_name = view.findViewById(R.id.happy_music_name);
        Music_play = view.findViewById(R.id.happy_music_play);
        Music_stop = view.findViewById(R.id.happy_music_stop);
        Music_refer = view.findViewById(R.id.happy_music_refer);
        Video_one = view.findViewById(R.id.happy_video_one);
        Video_two = view.findViewById(R.id.happy_video_two);
        Video_next_one = view.findViewById(R.id.happy_video_next_one);
        Video_next_two = view.findViewById(R.id.happy_video_next_two);
        bizhi = view.findViewById(R.id.happy_bizhi);
        touxiang = view.findViewById(R.id.happy_touxiang);
        bizhi_dow = view.findViewById(R.id.happy_bizhi_dow);
        touxiang_dow = view.findViewById(R.id.happy_touxiang_dow);
        game_one = view.findViewById(R.id.happy_game_one);
        game_two = view.findViewById(R.id.happy_game_two);
        game_three = view.findViewById(R.id.happy_game_three);
        game_forr = view.findViewById(R.id.happy_game_forr);
        Video_next_one_stop = view.findViewById(R.id.happy_video_next_one_stop);
        Video_next_two_stop = view.findViewById(R.id.happy_video_next_two_stop);
        vid_img1 = view.findViewById(R.id.vid_img1);
        vid_img2 = view.findViewById(R.id.vid_img2);
    }

    private void initUI() {
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(requireActivity(), Uri.parse("https://api.vvhan.com/api/rand.music?sort=热歌榜"));
            mediaPlayer.prepare();
            Music_name.setText("已准备播放.👋");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //播放歌曲
        Music_play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.start();
                Music_name.setText("正在播放中.🎵");
            }
        });
        //暂停歌曲
        Music_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.pause();
                Music_name.setText("暂停播放中.🥹");
            }
        });
        //刷新歌曲
        Music_refer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaPlayer.reset();
                int musicimgs = random.nextInt(10);
                try {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Music_icon.setImageResource(musicimg[musicimgs]);
                        }
                    });
                    /*int musicint = random.nextInt(13);
                    String music_url = "https://link.hhtjim.com/163/" + music[musicint] + ".mp3";
                    Music_name.setText(Musicname[musicint]);*/
                    Music_name.setText("正在播放中.🎵");
                    mediaPlayer.setDataSource(requireActivity(), Uri.parse("https://api.vvhan.com/api/rand.music?sort=热歌榜"));
                    mediaPlayer.prepare();
                    mediaPlayer.start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        Video_two.setPlayerFactory(ExoMediaPlayerFactory.create());
        int new_vedio = random.nextInt(650);
        Video_one.setUrl("https://cn-sy1.rains3.com/tc1/1%20(" + new_vedio + ").mp4");
        //播放视频
        Video_next_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vid_img1.setVisibility(View.GONE);
                Video_one.release();
                int tandom = random.nextInt(27);
                Video_one.setPlayerFactory(ExoMediaPlayerFactory.create());
                /*Video_one.setUrl(data[tandom]);*/
                int new_vedio = random.nextInt(650);
                Video_one.setUrl("https://cn-sy1.rains3.com/tc1/1%20(" + new_vedio + ").mp4");
                //Log.e("TAG", String.valueOf((int)tandom));
                Map<String, Object> music = new HashMap<String, Object>();
                music.put("美女热舞", "播放");//自定义参数：，值：
                MobclickAgent.onEventObject(requireActivity(), "Video_next_one", music);
                getPlay();
            }
        });
        Video_next_one_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TranslateAnimation showAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 3.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f);
                showAnim.setDuration(500);
                vid_img1.startAnimation(showAnim);
                vid_img1.setVisibility(View.VISIBLE);
                Video_one.pause();
            }
        });
        Video_next_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                vid_img2.setVisibility(View.GONE);
                Video_two.release();
                int tandom = random.nextInt(27);
                Video_two.setPlayerFactory(ExoMediaPlayerFactory.create());
                /*Video_two.setUrl(data[tandom]);*/
                int new_vedio = random.nextInt(650);
                Video_one.setUrl("https://cn-sy1.rains3.com/tc1/1%20(" + new_vedio + ").mp4");
                Map<String, Object> music = new HashMap<String, Object>();
                music.put("美女热舞", "播放");//自定义参数：，值：
                MobclickAgent.onEventObject(requireActivity(), "Video_next_one", music);
                getPlays();
            }
        });
        Video_next_two_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TranslateAnimation showAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 3.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f);
                showAnim.setDuration(500);
                vid_img2.startAnimation(showAnim);
                vid_img2.setVisibility(View.VISIBLE);
                Video_two.pause();
            }
        });

        game_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent();
                intent1.putExtra("网址", UrlData[0]);
                intent1.setClass(requireActivity(), GameWeb.class);
                startActivity(intent1);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });

        game_two.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.putExtra("网址", UrlData[1]);
                intent2.setClass(requireActivity(), GameWeb.class);
                startActivity(intent2);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        game_three.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.putExtra("网址", UrlData[3]);
                intent2.setClass(requireActivity(), GameWeb.class);
                startActivity(intent2);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });
        game_forr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent2 = new Intent();
                intent2.putExtra("网址", UrlData[2]);
                intent2.setClass(requireActivity(), GameWeb.class);
                startActivity(intent2);
                requireActivity().overridePendingTransition(R.anim.activity_visible, R.anim.activity_gone);
            }
        });

        //播放视频
        vid_img1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TranslateAnimation hideAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 3.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f);
                hideAnim.setDuration(500);
                vid_img1.startAnimation(hideAnim);
                vid_img1.setVisibility(View.GONE);
                /*Video_one.release();
                Video_one.setPlayerFactory(ExoMediaPlayerFactory.create());
                int new_vedio = random.nextInt(650);
                Video_one.setUrl("https://cn-sy1.rains3.com/tc1/1%20(" + new_vedio + ").mp4");
                getPlay();*/
                getPlay();
                Video_one.start();
            }

        });
        vid_img2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TranslateAnimation hideAnim = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 3.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f,
                        Animation.RELATIVE_TO_SELF, 0.0f);
                hideAnim.setDuration(500);
                vid_img2.startAnimation(hideAnim);
                vid_img2.setVisibility(View.GONE);
                getPlays();
                Video_two.start();
            }
        });
    }

    public void initStartData() {
        if (!Utlis.isVPNConnected(requireActivity())) {
            EasyHttp.get("http://api.btstu.cn/sjtx/api.php")
                    .params("lx", "a1")
                    .params("format", "json")
                    .execute(new SimpleCallBack<String>() {
                        @Override
                        public void onSuccess(String data) {
                            try {
                                JSONObject jsonObject = new JSONObject(data);
                                String jsondata = jsonObject.getString("imgurl");

                                // 更新UI操作
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Picasso.with(requireActivity()).load("https://api.vvhan.com/api/bing").noPlaceholder().error(R.mipmap.ic_load).into(bizhi);
                                        Picasso.with(requireActivity()).load(jsondata).noPlaceholder().error(R.mipmap.yujiazai).into(touxiang);
                                    }
                                });
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void onError(ApiException e) {
                            e.printStackTrace();
                        }
                    });
        }
    }

    //头像，壁纸
    public void Start() {
        bizhi_dow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Time t = new Time();
                String time = t.year + "年 " + (t.month + 1) + "月 " + t.monthDay + "日 " + t.hour + "h " + t.minute + "m " + t.second;
                Bitmap bitmap = ((BitmapDrawable) bizhi.getDrawable()).getBitmap();  //获取图片
                String bb = Utlis.fileSaveToPublic(view.getContext(), "BakImg" + t.second, bitmap);
                // mMyDialog.dismiss();
                Alerter.create((Activity) view.getContext())
                        .setDuration(1200)
                        .setTitle("壁纸已保存至相册！")
                        .setText("保存路径：" + bb)
                        .setBackgroundColorRes(R.color.fbutton_color_emerald)
                        .show();
            }
        });

        touxiang_dow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Time t = new Time();
                String time = t.year + "年 " + (t.month + 1) + "月 " + t.monthDay + "日 " + t.hour + "h " + t.minute + "m " + t.second;
                Bitmap bitmap = ((BitmapDrawable) touxiang.getDrawable()).getBitmap();  //获取图片
                String bb = Utlis.fileSaveToPublic(view.getContext(), "BakImg" + t.second, bitmap);
                // mMyDialog.dismiss();
                Alerter.create((Activity) view.getContext())
                        .setDuration(1200)
                        .setTitle("头像已保存至相册！")
                        .setText("保存路径：" + bb)
                        .setBackgroundColorRes(R.color.fbutton_color_emerald)
                        .show();
            }
        });

    }

    public void getPlay() {
        Video_one.addOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {

            }

            @Override
            public void onPlayStateChanged(int playState) {
                switch (playState) {
                    //调用release方法会回到此状态
                    case VideoView.STATE_IDLE:
                        break;
                    case VideoView.STATE_PLAYING:
                    case VideoView.STATE_PAUSED:
                    case VideoView.STATE_PREPARED:
                    case VideoView.STATE_ERROR:
                    case VideoView.STATE_BUFFERED:
                        break;
                    case VideoView.STATE_PREPARING:
                    case VideoView.STATE_BUFFERING:
                        break;
                    case VideoView.STATE_PLAYBACK_COMPLETED:
                        break;
                }
            }
        });


        Video_one.setVideoController(new GestureVideoController(requireActivity()) {
            @Override
            protected int getLayoutId() {
                return 0;
            }
        });
        Video_one.start();
    }

    public void getPlays() {
        Video_two.addOnStateChangeListener(new VideoView.OnStateChangeListener() {
            @Override
            public void onPlayerStateChanged(int playerState) {

            }

            @Override
            public void onPlayStateChanged(int playState) {
                switch (playState) {
                    //调用release方法会回到此状态
                    case VideoView.STATE_IDLE:
                        break;
                    case VideoView.STATE_PLAYING:
                    case VideoView.STATE_PAUSED:
                    case VideoView.STATE_PREPARED:
                    case VideoView.STATE_ERROR:
                    case VideoView.STATE_BUFFERED:
                        break;
                    case VideoView.STATE_PREPARING:
                    case VideoView.STATE_BUFFERING:
                        break;
                    case VideoView.STATE_PLAYBACK_COMPLETED:
                        break;
                }
            }
        });


        Video_two.setVideoController(new GestureVideoController(requireActivity()) {
            @Override
            protected int getLayoutId() {
                return 0;
            }
        });
        Video_two.start();

    }

    // Fragment页面onResume函数重载
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("fragment_happy"); //统计页面("MainScreen"为页面名称，可自定义)
    }

    // Fragment页面onResume函数重载
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("fragment_happy");
    }

}